import qs from 'querystring';
import fetch from 'fermionjs/lib/fetch';
import errorCodesBuilder from '../../helpers/errorCodesBuilder';
import { warnEventId } from '../../../common/warnId';

const errorCodes = errorCodesBuilder();

export default (config, server) =>
	async function cyd(job) {
		const api = config.api;
		let result;
		let createSslRes;
		try {
			createSslRes = await fetch(api, {
				headers: {
					'content-type': 'application/x-www-form-urlencoded',
				},
				method: 'POST',
				body: qs.stringify({
					...job.data,
					domain: job.data.target,
				}),
			});
			server.log.debug(
				{
					api: config.api,
					job: job.data,
					response: createSslRes,
				},
				'[QUEUE][CYD_SETTING]cyd_setting检查'
			);
		} catch (err) {
			const error = errorCodes['[07]创宇盾源站配置检查失败'].from(err);
			server.log.error(
				{ error, api: config.api, job: job.data },
				error.message
			);
			throw error;
		}

		if (createSslRes.code === 0) {
			job.progress(100);
			result = createSslRes.limited;
		}

		return {
			warnings: !result?.limited
				? [
						{
							id: warnEventId({
								taskType: 'cyd',
								id: 'source-limited',
							}),
							title: '创宇盾未限制请求IP',
							level: 3,
							detail: {
								risk: '高',
								recommendation: '限制只允许创宇盾节点IP请求',
							},
						},
				  ]
				: [],
		};
	};
